package midware

import (
	"runtime/debug"
	"shop/common/log"
	"shop/monitor"
	"shop/utils/result"
	"time"

	"github.com/gin-gonic/gin"
)

// Recover 自定义panic异常处理，并进行api打点记录
func Recover(c *gin.Context) {
	startTime := time.Now()
	defer func() {
		// api耗时计算
		cost := float64(time.Now().Sub(startTime).Milliseconds())
		monitor.HttpDurations.WithLabelValues(c.Request.Method, c.FullPath()).Observe(cost) // 毫秒
		log.Infof("api耗时: %.2f", cost)

		if err := recover(); err != nil {
			log.Errorf("panic err:%v", err)
			debug.PrintStack()
			result.RenderResult(c, result.Fail("server inner error(panic recover)"))
			// api-panic次数
			monitor.ApiCounter.WithLabelValues(c.Request.Method, c.FullPath(), "panic").Inc()
			c.Abort()
		}
	}()
	c.Next()
}
